package com.nervenets.shopping.controller.common.params;

import com.nervenets.general.Global;
import com.nervenets.general.exception.LogicException;
import com.nervenets.general.jwt.util.JwtUtils;
import com.nervenets.general.model.SecurityUser;
import com.nervenets.general.utils.GeoUtil;
import com.nervenets.general.web.params.FormParams;
import com.nervenets.shopping.enumeration.Gender;
import com.nervenets.shopping.exception.UserNotLoginException;
import com.nervenets.shopping.hibernate.domain.common.Address;
import com.nervenets.shopping.service.AddressService;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import lombok.experimental.SuperBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import java.util.List;

@EqualsAndHashCode(callSuper = true)
@Setter
@Getter
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder
public class AddressFormParams extends FormParams<Address, AddressService> {
    @ApiModelProperty(value = "姓名", required = true)
    @NotBlank
    @Size(max = 10)
    private String name;
    @ApiModelProperty(value = "性别", required = true)
    @NotNull
    private Gender gender;
    @ApiModelProperty(value = "手机号码", required = true)
    @Pattern(regexp = Global.RegExp.MOBILE, message = "请输入正确的手机号码")
    private String mobile;
    @ApiModelProperty(value = "地区IDs")
    private List<Long> areaIds;
    @ApiModelProperty(value = "详细地址")
    private String detail;
    @ApiModelProperty(value = "经度")
    private double longitude = 0;
    @ApiModelProperty(value = "纬度")
    private double latitude = 0;
    @ApiModelProperty(value = "是否设置为默认", required = true)
    private boolean def;

    @Override
    public Address validateAndBuild(AddressService service, HttpServletRequest request, HttpServletResponse response) {
        if (!GeoUtil.isValidChinaCoordinate(getLongitude(), getLatitude())) {
            throw new LogicException(HttpStatus.BAD_REQUEST.value(), "地址的经纬度错误！");
        }

        Address address = new Address();
        if (getFormId() > 0) {
            address = service.findOne(getFormId());
        }

        BeanUtils.copyProperties(this, address, Global.defaultIgnoreProperties());

        SecurityUser user = JwtUtils.getUser();
        if (null == user) throw new UserNotLoginException();

        address.setUserId(user.getId());
        service.save(address);

        if (isDef()) {
            service.updateOtherAddressDefToFalse(user.getId(), address);
        }
        return address;
    }
}
